<template>
  <div class="common-layout">
    <el-container>
      <!--头部-->
      <el-header>
        <el-menu
            :default-active="activeIndex"
            class="HomeChoose"
            mode="horizontal"
            :ellipsis="false"
            @select="handleSelect"
            router
        >
          <el-menu-item index="0">
            <img
                style="width: 60px"
                src="../assets/logo.png"
                alt="SC logo"
            />
          </el-menu-item>
          <div class="flex-grow"/>
          <el-menu-item index="home">
            <el-icon>
              <House/>
            </el-icon>
            首页
          </el-menu-item>
          <el-sub-menu :index="item.path" v-for="item in menu_data" :key="item.name">
            <template #title>
              <el-icon>
                <component :is="item.icon"></component>
              </el-icon>
              <span>{{item.name}}</span></template>
            <el-menu-item :index="child.path" v-for="child in item.child" :key="child.name">
              <el-icon>
                <component :is="child.icon"></component>
              </el-icon>
              {{child.name}}
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item index="announcement">
            <el-icon>
              <Help/>
            </el-icon>
            我的消息
          </el-menu-item>
          <el-menu-item index="3">
            <el-icon>
              <Phone/>
            </el-icon>
            联系我们
          </el-menu-item>


          <div class="IDpicture">
            <el-input v-model="input2" class="searchFunction" placeholder="请输入搜索的功能">
              <template #suffix>
                <el-icon class="el-input__icon">
                  <search/>
                </el-icon>
              </template>
            </el-input>
            <el-avatar
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            />
          </div>
        </el-menu>

      </el-header>

      <el-main>
        <el-row>
          <el-image style="width: 200px; height: 50px;margin-left: 8%;margin-top: 1%"
                    :src="require('@/assets/NEUSOFT.png')" :fit="fit"/>
          <el-input v-model="input2" class="searchGoods" placeholder="请输入搜索的商品">
            <template #suffix>
              <el-icon class="el-input__icon">
                <search/>
              </el-icon>
            </template>
          </el-input>
        </el-row>

        <el-container   class="deep-container" style="border-radius:20px;border: 2px solid #FCFCFC;box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.3); width: 90%; height: 100%;margin: auto;margin-top: 2%">
          <el-container>
            <el-header style="padding: 0;background-color: #FCFCFC;border-radius: 20px">
              <div style="font-family: Arial, sans-serif; font-size: 36px; font-weight: bold; margin-left: 60px;margin-top: 40px">我的购物车</div>
              <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
            </el-header>
            <el-main style="margin-top:4%;border-radius: 20px">
              <el-table :data="myCart" style="width: 100%;background-color:#FCFCFC;"  :header-cell-style="{backgroundColor:'#FCFCFC'}"
                        :cell-style="{backgroundColor:'#FCFCFC'}"
                        :row-style="{backgroundColor:'#FCFCFC'}"
                        height="650" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="100px" />
                <el-table-column  label="商品图片" width="150px" align="center">
                  <template #default="scope">
                    <img :src="scope.row.goodsURL" style="width: 100%; height: auto" /></template>
                </el-table-column>
                <el-table-column prop="goodsName" label="商品" width="200px" align="center"/>
                <el-table-column prop="goodsPrice" label="单价" width="200px" align="center"/>
                <el-table-column prop="goodsNum" label="数量" width="200px" align="center">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.cartNumber" :min="1"/>
                  </template>
                </el-table-column>
                <el-table-column prop="total" label="小计" width="200px" align="center">
                  <template #default="scope">
                    {{ parseFloat(scope.row.total).toFixed(2) }}
                  </template></el-table-column>
                <el-table-column prop="right" label="操作" width="200px" align="center">
                  <template #default="scope">
                    <el-button size="small" @click="deleteCarts(scope.row.cartId)" type="primary">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-main>
          </el-container>
          <el-aside width="300px">
            <el-container style="border-radius:20px;border: 2px solid #FCFCFC;background-color:#F1F1F1;
                                            width: 100%; height: 43%;margin: auto;margin-top: 35%">
              <el-header  style="background-color: #F1F1F1;padding:0;border-radius: 20px">
                <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 25px"><div>合计:</div><div style="margin-right: 30px">￥{{ltPrice}}</div></div>
                <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
                <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 25px"><div>运费:</div><div style="margin-right: 30px">￥8.00</div></div>
                <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
                <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 25px"><div>总计:</div><div style="margin-right: 30px">￥{{totalPrice}}</div></div>
                <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
                <div style="margin-left: 8%;"><el-button  style="width: 250px"@click="Pay" type="primary">结算</el-button></div><br/>
                <div style="margin-left: 8%"><el-button  style="width: 250px" @click="ContinuePay" type="">继续购物</el-button></div>
              </el-header>
            </el-container>
          </el-aside>
        </el-container>
      </el-main>
    </el-container>

    <el-dialog v-model="payVisible"  style="height: 90%;width: 90%;background-color: #FCFCFC" >
      <el-image style="width: 200px; height: 50px;margin-left: 8%;margin-top: 1%"
                :src="require('@/assets/NEUSOFT.png')" :fit="fit"/>
      <el-container   style="border-radius:20px;border: 2px solid #FCFCFC;box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.3); width: 90%; height: 600px;margin: auto;margin-top: 2%">
        <el-container>
          <el-header style="padding: 0;background-color: #FCFCFC;border-radius: 20px">
            <div style="font-family: Arial, sans-serif; font-size: 30px; font-weight: bold; margin-left: 60px;margin-top: 40px">创建订单</div>
            <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
          </el-header>
          <el-main style="margin-top:5%;border-radius: 20px;width: 100%">
            <el-table :data="selectedItem" style="width: 1200px;background-color:#FCFCFC;"  :header-cell-style="{backgroundColor:'#FCFCFC'}"
                      :cell-style="{backgroundColor:'#FCFCFC'}"
                      :row-style="{backgroundColor:'#FCFCFC'}"
                      height="420" >
              <el-table-column  label="商品图片" width="150px" align="center">
                <template #default="scope">
                  <img :src="scope.row.goodsURL" style="width: 100%; height: auto" /></template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品" width="250px" align="center"/>
              <el-table-column prop="goodsPrice" label="单价" width="250px" align="center"/>
              <el-table-column prop="cartNumber" label="数量" width="250px" align="center">
              </el-table-column>
              <el-table-column prop="total" label="小计" width="200px" align="center">
                <template #default="scope">
                  {{ parseFloat(scope.row.total).toFixed(2) }}
                </template></el-table-column>
            </el-table>
          </el-main>
        </el-container>
        <el-aside width="300px">
          <el-container style="border-radius:20px;border: 2px solid #FCFCFC;background-color:#F1F1F1;
                                            width: 100%; height: 80%;margin: auto;margin-top: 35%">
            <el-header  style="background-color: #F1F1F1;padding:0;border-radius: 20px">
              <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 20px;"><div>收货地址:</div><div style="margin-right: 120px">{{store.getters.getRoom}}</div></div>
              <el-divider style="margin-top: 15px;margin-left: 3%; width: 93%"></el-divider>
              <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 20px;"><div>联系电话:</div><div style="margin-right: 70px">{{store.getters.getPhone}}</div></div>
              <el-divider style="margin-top: 15px;margin-left: 3%; width: 93%"></el-divider>
              <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 20px;"><div>配送方式:</div><div style="margin-right: 65px">普通配送 包邮</div></div>
              <el-divider style="margin-top: 15px;margin-left: 3%; width: 93%"></el-divider>
              <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 15px"><div>运费:</div><div style="margin-right: 30px">￥8.00</div></div>
              <el-divider style="margin-top: 15px;margin-left: 3%; width: 93%"></el-divider>
              <div style="display: flex; justify-content: space-between;font-family: Arial, sans-serif; font-size: 17px; font-weight: bold;margin-left: 40px;margin-top: 15px"><div>总计:</div><div style="margin-right: 30px">￥{{totalPrice}}</div></div>
              <el-divider style="margin-top: 15px;margin-left: 3%; width: 93%"></el-divider>
              <div style="margin-left: 8%;"><el-button  style="width: 250px"@click="toPay" type="primary">支付</el-button></div><br/>
              <div style="margin-left: 8%"><el-button  style="width: 250px" @click="noPay" type="">取消</el-button></div>
            </el-header>
          </el-container>
        </el-aside>
      </el-container>
    </el-dialog>
    <!--支付弹窗-->
    <el-dialog v-model="payWay"  style="height: 90%;width: 90%;background-color: #FCFCFC" >
      <el-image style="width: 200px; height: 50px;margin-left: 8%;margin-top: 1%"
                :src="require('@/assets/NEUSOFT.png')" :fit="fit"/>
      <el-container   style="border-radius:20px;border: 2px solid #FCFCFC;box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.3); width: 90%; height: 600px;margin: auto;margin-top: 2%">
        <el-container>
          <el-header style="padding: 0;background-color: #FCFCFC;border-radius: 20px">
            <div style="font-family: Arial, sans-serif; font-size: 30px; font-weight: bold; margin-left: 60px;margin-top: 40px">订单支付</div>
            <el-divider style="margin-top: 20px;margin-left: 3%; width: 93%"></el-divider>
          </el-header>
          <el-main style="margin-top:5%;border-radius: 20px;width: 100%">
            <div style="font-family: Arial, sans-serif; font-size: 25px; font-weight: bold; margin-left: 40px;margin-top: 10px">支付类别<div style="font-family: 华文宋体, sans-serif; font-size: 18px; font-weight: lighter; margin-left: 5px;margin-top: 10px">购物</div></div>
            <el-divider style="margin-top: 20px;margin-left:1%; width: 95%"></el-divider>
            <div style="font-family: Arial, sans-serif; font-size: 25px; font-weight: bold; margin-left: 40px;margin-top: 10px">支付方式<br/>
              <el-checkbox v-model="payByWallet"  border   style="margin-top: 15px; width: 140px;height: 35px;display: flex;"><el-row><el-icon :size="21" style="margin-top: 1px"><Wallet /></el-icon><span style="margin-left: 10px;margin-top: 6px">钱包支付</span></el-row></el-checkbox></div>
            <el-divider style="margin-top: 20px;margin-left: 1%; width: 95%"></el-divider>
            <div style="font-family: Arial, sans-serif; font-size: 25px; font-weight: bold; margin-left: 40px;margin-top: 10px">支付金额<div style="font-family: 华文宋体, sans-serif; font-size: 34px; font-weight: bold; margin-left: 5px;margin-top: 10px;color: crimson">￥{{totalPrice}}</div></div>
            <el-row style="margin-left: 75%;margin-top: 20px">
              <div><el-button  style="width: 100px;border-color:black;height: 40px"@click="RefusePay" type="" >取消支付</el-button></div>
              <div style="margin-left: 20px"><el-button  style="width: 100px;height: 40px"@click="SuccessPay" type="primary">确认支付</el-button></div>
            </el-row>
          </el-main>
        </el-container>
      </el-container>
    </el-dialog>
  </div>
</template>

<script setup>
import *as allGoodsAPI from "../api/goods";
import {onMounted, ref,computed} from 'vue'
import {useStore} from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const selectedItem = ref([])
const selectedCarts=ref([])
const Cart=ref([])
const store=useStore()
const goods = ref([])
const activeIndex = ref('1')
const payWay=ref(false)
let payVisible=ref(false)
const payByWallet=ref(true)

const handleSelect = (index) => {
  activeIndex.value = index;
}
import router from "@/router";


const SuccessPay=()=>{
  const selectedItems = Cart.value.filter(cart => selectedCarts.value.includes(cart.cartId))
  // 显示弹窗并传入选中的购物车项
  payVisible.value = true
  selectedItem.value = JSON.parse(JSON.stringify(selectedItems))
  console.log("1")
  console.log(selectedItem.value)

  setTimeout(() => {
    const requestData = [];
    const deleteId=[];
    selectedItem.value.forEach(item => {

      const deleteObject={
        cartId:item.cartId
      }
      // 创建一个新对象，根据后端接口的需求添加相应的属性
      const dataObject = {
        storeId:item.storeId,
        goodsUrl:item.goodsURL,
        userId:item.userId,
        goodsId:item.goodsId,
        goodsName: item.goodsName,
        goodsPrice: item.goodsPrice,
        goodsTotal: item.cartNumber,
        goodsAddress:store.getters.getRoom,
        orderPhoneNumber:store.getters.getPhone,
        totalPrice: item.total
        // 可以根据需要添加更多属性
      };

      // 将转换后的对象添加到 requestData 数组中
      requestData.push(dataObject);
      deleteId.push(deleteObject)
    });
    if (Number(totalPrice.value)<=Number(store.getters.getMoney)){
      let lastMoney=0;
      payWay.value=false;
      payVisible.value=false;
      ElMessage({message: "支付成功",
        type:'success'});
      lastMoney=Number(store.getters.getMoney)-Number(totalPrice.value)
      console.log(lastMoney)
      store.commit("saveMoney",lastMoney)
      allGoodsAPI.UpdateWallet({userId:store.getters.getId,money:store.getters.getMoney}).then((res)=>{
        console.log(store.getters.getMoney)
      })
      allGoodsAPI.UpdateById({userId:store.getters.getId,money:store.getters.getMoney}).then((res)=>{
        console.log(store.getters.getMoney)
      })
      console.log("11111111111111111111")
      console.log(store.getters.getMoney)
      for (let i=0;i<requestData.length;i++){

        allGoodsAPI.InsertOrder(requestData[i]).then((res) => {
          // 处理 insertOrder 函数的返回结果
          console.log("添加");
          // 根据实际情况显示成功或失败的消息
          ElMessage({
            message: "订单提交成功",
            type: 'success'
          });
        })
        allGoodsAPI.addWallet({userId:store.getters.getId,userPayout:requestData[i].totalPrice,userBalance:store.getters.getMoney,outState:1}).then((res)=>{
          console.log("账单添加")
        })
        allGoodsAPI.CartDelete(deleteId[i]).then((res)=>{
          console.log("删除成功")
          window.location.reload();
        })

      };}
    else{
      return console.log("no money")
    }
  }, 3000); // 假设 3000ms 后加载完成
}
//支付弹窗
const toPay=()=>{
  // 显示弹窗并传入选中的购物车项
  payWay.value = true
}
const noPay=()=>{
  // 显示弹窗并传入选中的购物车项
  payVisible.value=false;
}
const RefusePay=()=>{
  // 显示弹窗并传入选中的购物车项
  payWay.value = false
}

const Pay=()=>{
  const selectedItems = Cart.value.filter(cart => selectedCarts.value.includes(cart.cartId))
  // 显示弹窗并传入选中的购物车项
  payVisible.value = true
  selectedItem.value = JSON.parse(JSON.stringify(selectedItems))
  console.log("pay...............")
  console.log(selectedItems)
  console.log(selectedItem.value)
  //console.log(Cart.value)
}

const ContinuePay=()=>{
  router.push("/Shophome");
}

const deleteCarts=(cartId)=>{
  ElMessageBox.confirm(
      '请确认是否删除？',
      '删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消删除',
        type: 'warning',
      }
  ).then(()=>{
    allGoodsAPI.CartDelete({cartId}).then((res)=>{
      console.log(res)
      ElMessage({
        type:'success',
        message:'删除成功',
      })
      window.location.reload();
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}

const GetMyCart=()=>{
  allGoodsAPI.MyCart({userId:store.getters.getId}).then((res) => {
    Cart.value = res.data;
    console.log(store.getters.getRoom)
  })
}

const myCart=computed(()=>{
  console.log(Cart.value)
  Cart.value.forEach((cart)=>{
    cart.total=cart.goodsPrice*cart.cartNumber
  })
  return Cart.value
})

const totalPrice = computed(()=>{
  let postPay=8;
  let myTotal=0;
  let allPrice=0
  console.log(myCart)
  Cart.value.forEach((cart)=>{
    if (selectedCarts.value.includes(cart.cartId)) {
      myTotal += cart.total;
      allPrice=postPay+myTotal
    }
  })
  return allPrice.toFixed(2);
})

const  ltPrice = computed(()=>{
  let postPay=8;
  let myTotal=0;
  let allPrice=postPay+myTotal
  console.log(myCart)
  Cart.value.forEach((cart)=>{
    if (selectedCarts.value.includes(cart.cartId)) {
      myTotal += cart.total
    }
  })
  return myTotal.toFixed(2);
})

const handleSelectionChange = (selection) => {
  selectedCarts.value = selection.map((item) => item.cartId) // 更新选中的购物车项
}

//页头多级菜单
const menu_data = ref([
  {
    name: '物业服务',
    icon: 'OfficeBuilding',
    path: '/community',
    child: [
      {
        name: '物业费缴纳',
        icon: 'ChatRound',
        path: '/stratafees',
      },
      {
        name: '车位管理',
        icon: 'Pointer',
        path: '/park',
      },
      {
        name: '报事维修',
        icon: 'ChatRound',
        path: '/maintenance',
      },
      {
        name: '事项投诉',
        icon: 'ChatRound',
        path: '/complaints',
      },
      {
        name: '访客登记',
        icon: 'ChatRound',
        path: '/visitor',
      },
    ]
  },
  {
    name: '商城',
    icon: 'Goods',
    path: '/shop',
    child: [
      {
        name: '商城首页',
        icon: 'Goods',
        path: '/shophome',
      },
      {
        name: '我的收藏',
        icon: 'Goods',
        path: '/collect',
      },
      {
        name: '我的购物车',
        icon: 'Goods',
        path: '/shoppingcart',
      },
      {
        name: '我的订单',
        icon: 'Goods',
        path: '/order',
      },
      {
        name: '我的钱包',
        icon: 'Goods',
        path: '/wallet',
      }
    ]
  },

])
onMounted(() => {
  GetMyCart()
})

const addSlash = (url) => {
  return `/${url}`
}

</script>

<style scoped>
.common-layout {
  width: 100%;
  height: 100%;
}

.common-layout .el-container {
  width: 100%;
  height: 100%;
}

.common-layout .el-header {
  background-color: white;
  height: 8%;
}

.common-layout .el-main {
  background-color: #FCFCFC;
  height: 90%;
  width: 100%;
}

.searchGoods {
  width: 46%;
  height: 50px;
  margin-left: 8%;
  margin-top: 30px;
  border-radius: 50px;
}

.searchFunction {
  height: 28px;
  width: 80%;
  right: 40px;
}
/*头部边框阴影*/


.HomeChoose {
  height: 100%;
  border: none;
  padding: 0;
  box-shadow: 0px 2px 0px 0 rgba(0, 0, 0, 0.1);
  display: flex;
}

.flex-grow {
  flex-grow: 0;
}

.IDpicture {
  text-align: right;
  display: flex;
  justify-content: flex-end; /* 让头像与其他内容分开排列 */
  align-items: center; /* 垂直居中对齐 */
  margin-left: 48%; /* 调整左右内边距 */
}
.card-margin{
  margin-right: 40px;
}
</style>